package cn.wolfcode.crm.service.impl;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PageUtils;

@Service
public class EmployeeServiceImpl  implements IEmployeeService{
    @Autowired
    private EmployeeMapper mapper;
    
    public void save(Employee entity) {
        mapper.insert(entity);
        //获取角色对象
        List<Role> roles = entity.getRoles();
        if(roles != null){
            for (Role role : roles) {
                //维护与角色的关系
                mapper.insertEmployeeAndRoleRelation(entity.getId(), role.getId());
            }
        }
    }

    public void update(Employee entity) {
    	//先删除旧的关系
    	mapper.deleteEmployeeAndRoleRelation(entity.getId());
    	
        mapper.updateByPrimaryKey(entity);       
        //获取角色对象
        List<Role> roles = entity.getRoles();
        if(roles != null){
            for (Role role : roles) {
                //维护与角色的新关系
                mapper.insertEmployeeAndRoleRelation(entity.getId(), role.getId());
            }
        }
    }

    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
        mapper.deleteEmployeeAndRoleRelation(id);
    }

    public List<Employee> list() {
        return mapper.selectAll();
    }

    public Employee get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public PageResult query(QueryObject qo) {
       return PageUtils.query(qo, mapper);
    }

	public Employee validateUsername(String username) {
		return mapper.checkUsername(username);
	}

	public void changeState(Long id) {
		mapper.changeState(id);
	}


    public void changePassword(String password) {
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        Long id = currentUser.getId();
        mapper.changePassword(password,id);
    }

}
